package lab03.text06;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;


public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        Map<String, Integer> map = new HashMap<>();

        String path = "F:\\worlds.txt";

        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(path, "r");
            while (true) {
                try {
                    String line = randomAccessFile.readLine();
                    if (line == null) {
                        break;
                    } else {
                        System.out.println(line);
                        String[] result = line.split(" ");

                        for (int i = 0; i < result.length; i++) {
                            list.add(result[i]);
                            set.add(result[i]);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("一共有" + list.size() + "个单词.");
        System.out.println("有" + set.size() + "个互不相同的单词");
        System.out.println("每个单词出现的频率分别为：");

        for (int i = 0; i < list.size(); i++) {
            map.put(list.get(i), Collections.frequency(list, list.get(i)));
        }

        List<Map.Entry<String, Integer>> mapSort = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(mapSort, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o2.getValue() - o1.getValue());
            }
        });

        for (int i = 0; i < mapSort.size(); i++) {
            String id = mapSort.get(i).toString();
            System.out.println(id);
        }
    }
}
